package edu.gxmzu.task.utils;

import java.io.File;
import java.io.FileInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * author: lrf
 * time: 2024-11-29
 * version : V1
 * detail: 附件上传处理
 * @return
 */
public class FileHashUtil {

    /**
     * @param filePath ：文件路径
     * @param algorithm ：编码
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static String getFileHash(String filePath, String algorithm) throws NoSuchAlgorithmException {
        MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
        try {
            File file = new File(filePath);
            FileInputStream fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int bytesRead;
            while ((bytesRead = fileInputStream.read(buffer)) != -1) {
                messageDigest.update(buffer, 0, bytesRead);
            }
        }catch (Exception e){
            e.printStackTrace();
        }

        // 将计算得到的哈希值转换为十六进制字符串
        StringBuilder hexString = new StringBuilder();
        for (byte b : messageDigest.digest()) {
            hexString.append(String.format("%02x", b));
        }
        return hexString.toString();
    }

}
